﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;

namespace Cloak.Mvp
{
	/// <summary>
	/// A mapping between view types and presenter references, cached by view type
	/// </summary>
	public sealed class CachingViewPresenterIndex : IViewPresenterIndex
	{
		private readonly Func<Type, IEnumerable<IPresenterReference>> _getPresenters;

		/// <summary>
		/// Initializes an index with the specified inner index
		/// </summary>
		/// <param name="innerIndex">The index whose results are cached</param>
		public CachingViewPresenterIndex(IViewPresenterIndex innerIndex)
		{
			Contract.Requires(innerIndex != null);

			_getPresenters = innerIndex.GetPresenters;

			_getPresenters = _getPresenters.Cached();
		}

		/// <summary>
		/// Gets the presenters mapped to the specified view type
		/// </summary>
		/// <param name="viewType">The type of view associated with the presenters</param>
		/// <returns>The presenters mapped to the specified type</returns>
		public IEnumerable<IPresenterReference> GetPresenters(Type viewType)
		{
			return _getPresenters(viewType);
		}
	}
}